package com.ls.markt.service.admin;

import com.ls.markt.dao.admin.ClubMapper;
import com.ls.markt.model.admin.Club;
import com.ls.markt.repository.admin.ClubRepository;
import com.ls.markt.util.ExcelUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
public class ClubService {

    @Resource
    private ClubMapper mapper;

    @Resource
    private ClubRepository clubRepository;

    /**
     * 保存，更新俱乐部
     * @param club
     */
    public void saveClub(Club club) {
        clubRepository.save(club);
    }

    public Club getClubById(Long id) {
        return clubRepository.getOne(id);
    }

    /**
     * 查询全部
     * @return
     */
    public List<Club> listClubs() {
        return clubRepository.findAll();
    }

    public List<Club> listClubsBylevel(Long level){
        return clubRepository.findByLevel(level);
    }

    /**
     * 分页查询全部
     * @param pageRequest
     * @return
     */
    public Page<Club> listClubs(PageRequest pageRequest) {
        return clubRepository.findAll(pageRequest);
    }

    /**
     * 批量删除俱乐部
     * @param ids
     */
    public void removeClub(Long[] ids) {
        for (Long id:ids){
            clubRepository.deleteById(id);
        }
    }

    /**
     * 根据id获取俱乐部名称
     * @param id 主键id
     * @return
     */
    public String getClubName(Long id) {
        return mapper.getNameById(id);
    }

    public Long getIdByName(String name){
        return mapper.getIdByName(name);
    }

    public int getClubNumberByLevel(Long level){
        return mapper.getClubNumberByLevel(level);
    }

    @Transactional
    public void importExcel(MultipartFile file) throws IOException {
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
//        EasyExcel.read(filename, Club.class, new ClubListener(mapper)).sheet().doRead();
//        EasyExcel.read(file.getInputStream(),Club.class, new ClubListener(mapper)).sheet().doRead();
        List<Object> clubs = ExcelUtil.readExcel(file,Club.class);
        for (Object o: clubs){
            Club club = (Club) o;
            clubRepository.save(club);
        }
    }
}
